import {
    domain,
    server,
    mockServer
} from './profile.js'

let useMock = true;

var requestHandler = {
    uri: '',
    params: {isMock: false},
    success: (res) => {
        // success
    },
    fail: (res) => {
        // fail
    },
    complete: (res) => {
        // complete
    }
}

//GET请求  
function GET(requestHandler, _withToken) {
    var withToken = _withToken || 1
    return request('GET', requestHandler, withToken)
}

//POST请求
function POST(requestHandler, _withToken) {
    var withToken = _withToken || 1
    return request('POST', requestHandler, withToken)
}

//PUT请求
function PUT(requestHandler, _withToken) {
    var withToken = _withToken || 1
    return request('PUT', requestHandler, withToken)
}

//DELETE请求
function DELETE(requestHandler, _withToken) {
    var withToken = _withToken || 1
    return request('DELETE', requestHandler, withToken)
}

//GET请求  
function GETOrigin(requestHandler, _withToken) {
    var withToken = _withToken || 1
    requestOrigin('GET', requestHandler, withToken)
}

//POST请求
function POSTOrigin(requestHandler, _withToken) {
    var withToken = _withToken || 1
    requestOrigin('POST', requestHandler, withToken)
}

//PUT请求
function PUTOrigin(requestHandler, _withToken) {
    var withToken = _withToken || 1
    requestOrigin('PUT', requestHandler, withToken)
}

//DELETE请求
function DELETEOrigin(requestHandler, _withToken) {
    var withToken = _withToken || 1
    requestOrigin('DELETE', requestHandler, withToken)
}

function requestOrigin(method, requestHandler, withToken) {
    //1：带，2：不带
    const requestTask = wx.request({
        url: (!!useMock && !!requestHandler.params && !!requestHandler.params.isMock ? mockServer : server) + requestHandler.uri,
        data: requestHandler.params,
        method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        header: { // 设置请求的 header
            //"content-Type": "application/x-www-form-urlencoded;charset=utf-8"
            "Authorization": (withToken === 1 ? wx.getStorageSync('token') : 'mini -1'),
            "Content-Type": (method === 'GET' ? "application/x-www-form-urlencoded;charset=utf-8" : "application/json;charset=utf-8")
        },
        success: (res) => {
            //注意：可以对参数解密等处理
            if (requestHandler.success) {
                if (res.data.code == 200) {
                    requestHandler.success(res.data)
                } else {
                    if (requestHandler.fail) {
                        requestHandler.fail(res.data)
                    } else {
                        wx.showToast({
                            title: res.data.message,
                            icon: 'none'
                        })
                    }
                }
            }
        },
        fail: (res) => {
            if (requestHandler.fail) {
                requestHandler.fail(res.data)
            }
        },
        complete: (res) => {
            if (requestHandler.complete) {
                requestHandler.complete(res.data)
            }
        }
    })
    return requestTask
}

async function request(method, requestHandler, withToken) {
    if (withToken == 1) {
        await checkToken()
    }
    requestPromise(method, requestHandler, withToken)
        .then(res => {
            if (requestHandler.success) {
                if (res.code == 200) {
                    requestHandler.success(res)
                } else {
                    if (requestHandler.fail) {
                        requestHandler.fail(res)
                    } else {
                        wx.showToast({
                            title: res.message || '',
                            icon: 'none'
                        })
                    }
                }
            }
            if (requestHandler.complete) {
                requestHandler.complete(res)
            }
        })
        .catch(res => {
            if (requestHandler.fail) {
                requestHandler.fail(res)
            } else {
                if (res) {
                    if (res.code == 101) { // 支付通道关闭错误码
                        wx.hideLoading()
                        wx.showModal({
                            title: '提示',
                            content: res.message,
                            showCancel: false
                        })
                    } else {
                        wx.showToast({
                            title: res.message || '',
                            icon: 'none'
                        })
                    }
                } else {
                    wx.showToast({
                        title: '网络异常，请稍后访问',
                        icon: 'none'
                    })
                }
            }
        })
}

function requestPromise(method, requestHandler, withToken) {
    return new Promise((resolve, reject) => {
        wx.request({
            url: (!!useMock && !!requestHandler.params && !!requestHandler.params.isMock ? mockServer : server) + requestHandler.uri,
            data: requestHandler.params,
            method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            header: { // 设置请求的 header
                //"content-Type": "application/x-www-form-urlencoded;charset=utf-8"
                "Authorization": (withToken === 1 ? wx.getStorageSync('token') : 'mini -1'),
                "Content-Type": (method === 'GET' ? "application/x-www-form-urlencoded;charset=utf-8" : "application/json;charset=utf-8")
            },
            dataType: 'json',
            success: (res) => {
                //注意：可以对参数解密等处理
                if (res.data.code == 200) {
                    resolve(res.data)
                } else {
                    reject(res.data)
                }
            },
            fail: (res) => {
                reject(res.data)
            }
        })
    })
}

function checkToken() {
    return new Promise(resolve => {
        const token = wx.getStorageSync('token')
        if (token) {
            resolve()
        } else {
            setTimeout(function () {
                checkToken().then(res => resolve(res));
            }, 150)
        }
    })
}

/**
 *
 */
function reqPromise(method, requestHandler) {
    return new Promise((resolve, reject) => {
        requestPromise(method, requestHandler, 1).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

/**
 * 上传文件方法
 * @param file 获取到的文件对象
 * @returns {Promise<unknown>}
 */
function uploadFile(file) {
    const token = wx.getStorageSync('token');
    return new Promise((resolve, reject) => {
        wx.uploadFile({
            url: domain + '/api/app/attachment', // 仅为示例，非真实的接口地址
            filePath: file.url,
            name: 'file',
            header: {
                "Authorization": (token ? token : 'mini -1'),
                'Content-Type': 'multipart/form-data;charset;charset=utf-8'
            },
            dataType: 'json',
            success(res) {
                const data = JSON.parse(res.data);
                if (res.statusCode === 200 && data.code === 200) {
                    resolve(data)
                } else {
                    reject(data)
                }
            },
            fail(res) {
                reject(res)
            }
        });
    })
}

module.exports = {
    requestHandler: requestHandler,
    GET: GET,
    POST: POST,
    PUT: PUT,
    DELETE: DELETE,
    GETOrigin: GETOrigin,
    POSTOrigin: POSTOrigin,
    PUTOrigin: PUTOrigin,
    DELETEOrigin: DELETEOrigin,
    reqPromise: reqPromise,
    SERVER: server,
    uploadFile: uploadFile
}